using Basket.Api.Data;
using Basket.Api.Domain;
using BuildingBlocks.Application.Authentication;
using BuildingBlocks.Application.Messaging;
using BuildingBlocks.Domain;
using Microsoft.EntityFrameworkCore;

namespace Basket.Api.Features.Baskets.GetBasket;

internal sealed class GetBasketQueryHandler(BasketDbContext dbContext,
    ICurrentUser currentUser)
    : IQueryHandler<GetBasketQuery, BasketResponse>
{
    public async ValueTask<Result<BasketResponse>> Handle(
        GetBasketQuery request,
        CancellationToken ct)
    {
        Guid userId = currentUser.UserId;

        var basket = await dbContext.Baskets
            .AsNoTracking()
            .Include(b => b.Items)
            .FirstOrDefaultAsync(b => b.UserId == userId, ct);

        if (basket is null)
        {
            return Result.Failure<BasketResponse>(BasketErrors.NotFound(userId));
        }

        List<BasketItemResponse> items = basket.Items
            .Select(item => new BasketItemResponse(
                item.ProductId,
                item.ProductName,
                item.UnitPrice,
                item.Quantity))
            .ToList();

        decimal total = items.Sum(i => i.UnitPrice * i.Quantity);

        return Result.Success(new BasketResponse(
            basket.UserId,
            items,
            total,
            basket.UpdatedAt));
    }
}
